# coding:utf-8
import json
import os
import sys
import random
from datetime import datetime
import pandas as pd
import scipy

from PyQt6.QtCharts import QLineSeries, QChart, QChartView
from PyQt6.QtCore import Qt, QUrl, pyqtSignal
from PyQt6.QtGui import QIcon, QPainter
from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QLabel, QVBoxLayout, QStackedWidget

from qfluentwidgets import MessageBoxBase, SubtitleLabel, LineEdit, PushButton, setTheme, Theme, SegmentedWidget

class ChartInterface(QWidget):

    def __init__(self, data_name, parent = None, inpectioninterface = None):
        super().__init__()
        self.parent = parent
        self.inpectioninterface = inpectioninterface.ui
        data_path = "./data/temp/data_"+str(data_name)+".json"
        self.chart = QChart()
        self.chart.setTitle("Line Chart")

        self.series = QLineSeries()
        #根据path，找到json文件，然后找到x，y的两个数组
        self.index,self.listx,self.listy = self.load_data_from_json(data_path)
        for i in range(len(self.listx)):
            self.series.append(self.listx[i],self.listy[i])

        # for i in range(100):
        #     self.series.append(i, random.randint(1, 100))  # 添加随机数据，可根据实际情况修改
        # for x, y in zip(x_data, y_data):
        #     series.append(x, y)

        self.chart.addSeries(self.series)
        self.chart.createDefaultAxes()
        self.chart_view = QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.RenderHint.Antialiasing)
        self.chart_view.setRubberBand(QChartView.RubberBand.RectangleRubberBand)
        self.chart_view.setInteractive(True)  # 允许交互操作
        self.chart_view.setMouseTracking(True)  # 开启鼠标追踪
        #self.chart_view.setFixedSize(800,300) #改变大小

        layout = QVBoxLayout()
        layout.addWidget(self.chart_view)
        self.setLayout(layout)
        self.setFixedSize(700,330)
        self.parent.signal_save_file.connect(self.save_file)

    def load_data_from_json(self, filename):
        with open(filename, "r") as json_file:
            data = json.load(json_file)
            index = data["index"]
            listx = data["listx"]
            listy = data["listy"]
            return index, listx, listy

    def save_lists_to_csv(self, folder_path, filename):
        # 将数据转换为DataFrame
        df = pd.DataFrame({'listx': self.listx, 'listy': self.listy})
        # 将数据转换为DataFrame，并转置
        #df = pd.DataFrame([self.listx, self.listy]).transpose()

        # 检查文件夹路径是否存在，如果不存在则创建
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        # 拼接文件路径
        file_path = os.path.join(folder_path, filename)

        # 将DataFrame保存为CSV文件
        df.to_csv(file_path, index=False, header=False)

    def save_file(self):
        csv_folder_name = self.inpectioninterface.data_folder_name_LineEdit.text()
        print("槽函数开始保存文件")
        data = {"index": self.index, "listx": self.listx, "listy": self.listy}

        json_data = json.dumps(data)
        # 创建data文件夹（如果不存在）
        temp_folder = "./data"
        csv_folder = f"./data/csv/{csv_folder_name}"

        os.makedirs(temp_folder, exist_ok=True)
        os.makedirs(csv_folder, exist_ok=True)
        # 构建文件名并保存JSON文件
        # 获取当前时间
        current_time = datetime.now()
        # 格式化当前时间
        formatted_time = current_time.strftime("%Y_%m_%d_%H_%M_%S_%f")
        # 输出格式化后的时间
        print(f"保存文件名：data_{formatted_time}.json")

        filename = os.path.join(temp_folder, f"data_{formatted_time}.json")
        with open(filename, "w") as json_file:
            json_file.write(json_data)

        csv_filename =  f"csv_{formatted_time}.csv"
        self.save_lists_to_csv(csv_folder,csv_filename)
        print(f"保存文件名：{csv_filename}")
        absolute_path = os.path.abspath(csv_folder)
        os.system("explorer.exe %s" % absolute_path)


class ChartMessageBox(MessageBoxBase):
    signal_save_file = pyqtSignal()
    """ Chart message box """
    def __init__(self,data_path, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.vBoxLayout = QVBoxLayout(self)  # 垂直布局
        self.titleLabel = SubtitleLabel('数据表格', self)#标题
        self.stackedWidget = QStackedWidget(self)
        self.pivot = SegmentedWidget(self)

        # 实例化 ChartInterface 类
        self.chart_interface = ChartInterface(data_path,parent=self,inpectioninterface=self.parent)
        self.ContrastInterface = QLabel('ContrastInterface',self)
        self.OtherInterface = QLabel('OtherInterface',self)

        #add items to pivot
        self.addSubInterface(self.chart_interface, 'ChartInterface', 'Chart')
        self.addSubInterface(self.ContrastInterface, 'ContrastInterface', 'Contrast')
        self.addSubInterface(self.OtherInterface, 'OtherInterface', 'Other')

        #self.data_folder_name_LineEdit = LineEdit(parent=self.vBoxLayout)

        # add widget to view layout
        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addLayout(self.vBoxLayout)
        self.vBoxLayout.addWidget(self.pivot)
        #self.vBoxLayout.addItem(self.data_folder_name_LineEdit)
        self.vBoxLayout.addWidget(self.stackedWidget)
        self.vBoxLayout.setContentsMargins(30, 10, 30, 30)


        # change the text of button
        self.yesButton.setText('保存')
        self.cancelButton.setText('取消')

        self.widget.setMinimumWidth(350)
        #self.yesButton.setDisabled(True)

        self.stackedWidget.currentChanged.connect(self.onCurrentIndexChanged)
        self.stackedWidget.setCurrentWidget(self.chart_interface)
        self.pivot.setCurrentItem(self.chart_interface.objectName())
        #点击保存按钮，输入名称并保存json文件
        self.yesButton.clicked.connect(self.emit_save_file)
        #self.hideYesButton()

    def emit_save_file(self):
        print("发送保存信号")
        self.signal_save_file.emit()

    def onCurrentIndexChanged(self, index):
        widget = self.stackedWidget.widget(index)
        self.pivot.setCurrentItem(widget.objectName())

    def addSubInterface(self, widget, objectName, text):
        widget.setObjectName(objectName)
        #widget.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.stackedWidget.addWidget(widget)
        self.pivot.addItem(
	        routeKey=objectName,
	        text=text,
	        onClick=lambda: self.stackedWidget.setCurrentWidget(widget),
        )
    def _validateUrl(self, text):
        self.yesButton.setEnabled(QUrl(text).isValid())